<script lang="ts" setup>
import { ElForm } from 'element-plus'
import { phoneRule, required } from '@utils/form-rule'
import {
  getScanQRCodesStateAPI,
  getWxQRCodeAPI,
  loginBySmsAPI,
  loginByUsernameAPI,
  loginByWxQRCodeAPI,
  sendNoteCodeAPI
} from '@/api/system'
import Authorization from '@utils/authorization'
import { ref } from 'vue'
import { CountDownTimer } from '@/utils'
import { setToken } from '@utils/authorization/token'
import { WxUtil } from '@utils/wx-util'
import wx from 'weixin-js-sdk'
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'
import { LoadingSvg } from '@assets/styles/loading'

const router = useRouter()

onMounted(() => {
  WxUtil.isWxEnv().then((res) => {
    if (res) {
      wx.miniProgram.postMessage({ data: { code: 401 } });
      (wx.miniProgram as NonNullable<any>).navigateBack()
    }
  })
  Authorization.token && router.push({ name: 'BoardIndex' })
})

// region TODO 登录表单
const loginForm = ref({
  username: '',
  password: '',
  phone: '',
  smsCode: '',
  autoLogin: false
})
const loginFormRef = shallowRef<InstanceType<typeof ElForm>>()
const loginFormRules = ref({
  username: [required('请输入账号/手机号')],
  password: [required('请输入密码')],
  phone: [required('请输入手机号'), phoneRule],
  smsCode: [required('请输入验证码')]
})
// endregion

// region TODO 登录方式
// username: 账号密码登录； phone手机号验证登录；qrcode二维码登录
const tabActive = ref<'username' | 'phone'>('username')
// endregion

// region TODO 登录表单提交
function formSubmitHandle () {
  loginFormRef.value.validate().then(() => {
    tabActive.value === 'username' ? usernameLogin() : phoneLogin()
  })
}
// endregion

// region TODO 账号密码登录
function usernameLogin () {
  const loading = ElLoading.service({ text: '正在登录...' })
  loginByUsernameAPI(loginForm.value).then(function (res) {
    res.result().then(function (rdata) {
      setToken(rdata.data)
      router.replace({ name: 'BoardIndex' })
    })
  }).finally(loading.close)
}
// endregion

// region TODO 手机号验证码登录
function phoneLogin () {
  const loading = ElLoading.service({ text: '正在登录...' })
  loginBySmsAPI(loginForm.value).then(function (res) {
    res.result().then(function (rdata) {
      setToken(rdata.data)
      router.replace({ name: 'BoardIndex' })
    })
  }).finally(loading.close)
}
// endregion

// region TODO 发送验证码
// 剩余倒计时
const remainingCountdown = ref(0)
const loginAuthCodeCountDownTimer = new CountDownTimer({
  key: 'loginAuthCode',
  toCookie: true,
  fn (e) {
    remainingCountdown.value = e
  }
})

// TODO 发送验证码
// 发送验证码
function sendVerificationCode () {
  loginFormRef.value.validateField(['phone']).then(() => {
    if (loginForm.value.phone) {
      const loading = ElLoading.service({ text: '正在发送...' })
      sendNoteCodeAPI({
        phone: loginForm.value.phone,
        type: 0
      }).then((res) => {
        res.result().then(() => {
          ElMessage.success('短信已发送，注意查收')
          loginAuthCodeCountDownTimer.run(60)
        })
      }).finally(loading.close)
    }
  })
}
// endregion

// region TODO 跳转页面
// 注册
function toRegister () {
  router.replace({ name: 'Register' })
}

// 忘记密码
function toRetrievePassword () {
  router.push({ name: 'RetrievePassword' })
}
// endregion

</script>

<template>
  <div class="login-container d-flex-center">
    <div class="d-flex" style="height: 512px;">
      <!--插画-->
      <img class="illustration" src="./images/illustration.png" style="width: 704px;height: 516px" alt="">
      <!--表单容器-->
      <div class="form-container mt-20">
        <div style="padding: 0 60px;">
          <!--账号密码登录 & phone手机号验证登录-->
          <div v-if="['username', 'phone'].includes(tabActive)">
            <el-tabs v-model="tabActive" class="c_tabs-default w-fit mx-auto">
              <el-tab-pane label="账号登录" name="username" />
              <el-tab-pane label="手机号登录" name="phone" />
            </el-tabs>
            <!--登录表单-->
            <el-form
              ref="loginFormRef"
              class="mt-36"
              size="large"
              :model="loginForm" :rules="loginFormRules"
              @submit.prevent="formSubmitHandle"
            >
              <!--账号密码登录-->
              <template v-if="tabActive === 'username'">
                <el-form-item prop="username">
                  <el-input v-model.trim="loginForm.username" placeholder="请输入账号/手机号">
                    <template #prefix><ic-system-avatar /></template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model.trim="loginForm.password" placeholder="请输入密码" show-password>
                    <template #prefix><ic-system-lock /></template>
                  </el-input>
                </el-form-item>
              </template>
              <!--手机号验证码登录-->
              <template v-else>
                <el-form-item prop="phone">
                  <el-input v-model.trim="loginForm.phone" placeholder="请输入手机号">
                    <template #prefix><ic-system-phone /></template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="smsCode">
                  <el-input v-model.trim="loginForm.smsCode" placeholder="请输入验证码">
                    <template #prefix><ic-system-safe /></template>
                    <template #append>
                      <el-button :disabled="remainingCountdown > 0" style="width: 110px;" @click="sendVerificationCode">
                        <span v-if="remainingCountdown">{{ remainingCountdown }}秒后重试</span>
                        <span v-else class="color-primary">获取验证码</span>
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
              <!--自动登录 & 忘记密码-->
              <div class="d-flex-between-center " style="height: 16px">
                <el-checkbox v-model="loginForm.autoLogin" label="30天内自动登录" class="color-secondary" style="font-size: 12px;" />
                <el-link type="primary" class="fs-12" @click="toRetrievePassword">忘记密码？</el-link>
              </div>
              <!--立即登录-->
              <el-form-item class="mt-28">
                <el-button class="form_btn-submit" native-type="submit" type="primary">立即登录</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!--qrcode二维码登录-->
          <template v-if="tabActive === 'qrcode'">
            <!--标题-->
            <div class="text-center">
              <div class="fs-20 text-color-primary">扫码登录</div>
              <div class="fs-12 text-color-regular mt-2">使用微信扫码登录</div>
            </div>
            <div
              ref="QRCodeRef" v-loading="WxQRCodeLoading" :element-loading-svg="LoadingSvg"
              class="my-20 mx-auto"
              style="width: 230px;aspect-ratio: 1;"
            >
              <img v-if="WxQRCodeUrl" :src="WxQRCodeUrl" alt="" class="wh-100">
            </div>
            <div class="text-center">
              <el-checkbox v-model="loginForm.autoLogin" label="30天内自动登录" class="color-secondary" style="font-size: 12px;" />
            </div>
          </template>
          <!--立即注册-->
          <div class="fs-12 d-flex-center mt-16">
            <el-divider />
            <div style="white-space: nowrap" class="mx-12 color-secondary">
              <span>还没账号？</span>
              <el-link type="primary" class="d-inline vertical-align-top fs-12" @click="toRegister">立即注册</el-link>
            </div>
            <el-divider />
          </div>
        </div>
      </div>
    </div>
    <!--版权-->
    <p class="copyright">Copyright © 2023 Yuankong Info All Rights Reserved</p>

    <el-dialog
      v-model="bindPhoneDialogModel" title="绑定手机号" :show-close="false"
      :close-on-click-modal="false"
      width="350px"
    >
      <el-form
        ref="bindPhoneFormRef" :model="bindPhoneForm" :rules="bindPhoneFormRules"
        size="large"
        style="margin: -10px 0 -20px 0;"
      >
        <el-form-item prop="phone">
          <el-input v-model.trim="bindPhoneForm.phone" placeholder="请输入手机号">
            <template #prefix><ic-system-phone /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <el-input v-model.trim="bindPhoneForm.smsCode" placeholder="请输入验证码">
            <template #prefix><ic-system-safe /></template>
            <template #append>
              <el-button :disabled="bindPhoneRemainingCountdown > 0" style="width: 110px;" @click="bindPhoneSendVerificationCode">
                <span v-if="bindPhoneRemainingCountdown">{{ bindPhoneRemainingCountdown }}秒后重试</span>
                <span v-else class="color-primary">获取验证码</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="cancelLogin">取消登录</el-button>
          <el-button type="primary" @click="bindPhoneSubmitHandle">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
//页面
.login-container {
  height: 100vh;
  min-height: 700px;
  background: url("./images/bg-login.png") top / 100% 100%;
  position: relative;
  > div {
    width: 1225px;
    justify-content: space-between;
  }
}
@media screen and (max-width: 1233px) {
  .login-container {
    > div {
      width: fit-content;
      justify-content: center;
    }
    .illustration {
      display: none;
    }
  }
}
//表单
.form-container {
  padding: 32px 8px 60px;
  width: 428px;
  height: fit-content;
  border-radius: 10px;
  background-color: white;
  //登录按钮
  .form_btn-submit {
    width: 100%;
    //--el-button-text-color: #FFFFFF;
    //--el-button-bg-color: var(--el-color-primary);
    //--el-button-hover-bg-color: var(--yk-color-primary-light-3);
    //--el-button-hover-text-color: #FFFFFF;
    font-size: 14px;
  }
  //输入框input前缀
  ::v-deep(.el-input__prefix) {
    font-size: 18px;
  }
}
 //标签栏
::v-deep(.c_tabs-default) {
  .el-tabs__item {
    font-weight: bold;
    font-size: 16px;
  }
}
// 版权
.copyright {
  color: var(--yk-color-secondary);
  position: absolute;
  inset: auto 0 40px 0;
  font-size: 12px;
  width: fit-content;
  margin: auto;
}
</style>
